use sqlx::{Database, Executor, FromRow, Postgres};

use crate::sql::{
    dialects::schema::{self, schema::Schema as _},
    schema::table::TableSchema,
    utils::pair::Pair,
};

use super::builder::ExecuteBuilder;

#[derive(Debug)]
pub struct InsertBuilder<'a> {
    table: TableSchema,
    default_schema: &'a str,
    columns: Vec<Pair>,
}

impl<'a> InsertBuilder<'a> {
    pub fn new(table: TableSchema) -> Self {
        Self {
            table,
            default_schema: "",
            columns: vec![],
        }
    }

    pub fn with_default_schema(mut self, schema: &'a str) -> Self {
        self.default_schema = schema;
        self
    }

    pub fn set(mut self, pair: Pair) -> Self {
        self.columns.push(pair);
        self
    }
}

impl<'a> ExecuteBuilder for InsertBuilder<'a>
// <DB as sqlx::Database>::Arguments<'a>: IntoArguments<'a, DB>,
{
    #[cfg(feature = "postgres")]
    type DB = Postgres;

    async fn execute<C>(
        &self,
        conn: &mut C,
    ) -> Result<<Self::DB as Database>::QueryResult, sqlx::Error>
    where
        for<'e> &'e mut C: Executor<'e, Database = Self::DB>,
    {
        let schema = schema::new(self.default_schema.to_string());
        let cols: Vec<String> = self.columns.iter().map(|c| c.name.to_string()).collect();
        let sql = schema.sql_insert_columns(&self.table, &cols, false);

        let mut query: sqlx::query::Query<'_, Self::DB, <Self::DB as Database>::Arguments<'_>> =
            sqlx::query::<Self::DB>(&sql);

        for col in &self.columns {
            query = col.value.bind_to_query(query);
        }

        // tracing::debug!("easy-sqlx: {}", query.sql());

        let result = query.execute(conn).await.map_err(|err| {
            tracing::error!(
                "easy-sqlx: {} [{}]\n{:?}",
                sql,
                &self
                    .columns
                    .iter()
                    .map(|c| { c.value.as_string() })
                    .collect::<Vec<String>>()
                    .join(","),
                err
            );
            err
        })?;

        #[cfg(feature = "logsql")]
        {
            tracing::info!(
                "easy-sqlx: {sql} [{}]\nnrows_affected: {}",
                &self
                    .columns
                    .iter()
                    .map(|c| { c.value.as_string() })
                    .collect::<Vec<String>>()
                    .join(","),
                result.rows_affected()
            );
        }

        Ok(result)
    }

    #[cfg(feature = "postgres")]
    async fn execute_return<'e, 'c: 'e, C, O>(&self, executor: C) -> sqlx::Result<Vec<O>>
    where
        C: 'e + Executor<'c, Database = Self::DB>,
        O: 'e,
        for<'r> O: FromRow<'r, <Self::DB as Database>::Row>,
        O: std::marker::Send,
        O: Unpin,
    {
        let schema = schema::new(self.default_schema.to_string());
        let cols: Vec<String> = self.columns.iter().map(|c| c.name.to_string()).collect();
        let sql = schema.sql_insert_columns(&self.table, &cols, true);

        let mut query = sqlx::query_as::<Self::DB, O>(&sql);

        for col in &self.columns {
            query = col.value.bind_to_query_as(query);
        }

        // tracing::debug!("easy-sqlx: {}", query.sql());

        let result: Result<Vec<O>, sqlx::Error> = query.fetch_all(executor).await.map_err(|err| {
            tracing::error!(
                "easy-sqlx: {} [{}]\n{:?}",
                sql,
                &self
                    .columns
                    .iter()
                    .map(|c| { c.value.as_string() })
                    .collect::<Vec<String>>()
                    .join(","),
                err
            );
            err
        });

        #[cfg(feature = "logsql")]
        {
            tracing::info!(
                "easy-sqlx: {sql} [{}]",
                &self
                    .columns
                    .iter()
                    .map(|c| { c.value.as_string() })
                    .collect::<Vec<String>>()
                    .join(",")
            );
        }

        result
    }
}
